package com.chanven.lib.cptr.loadmore;

import android.content.Context;
import androidx.core.view.ViewCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import com.chanven.lib.cptr.loadmore.ILoadViewMoreFactory.FootViewAdder;
import com.chanven.lib.cptr.loadmore.ILoadViewMoreFactory.ILoadMoreView;

public class WebViewHandler implements ViewHandler {

    @Override
    public boolean handleSetAdapter(View contentView, ILoadMoreView loadMoreView, OnClickListener onClickLoadMoreListener) {
        final ScrollWebView webView = (ScrollWebView) ((ViewGroup)contentView).getChildAt(0);
        boolean hasInit = false;
        if (loadMoreView != null) {
            final Context context = webView.getContext().getApplicationContext();
            loadMoreView.init(new FootViewAdder() {

                @Override
                public View addFootView(int layoutId) {
                    View view = LayoutInflater.from(context).inflate(layoutId, webView, false);
                    return addFootView(view);
                }

                @Override
                public View addFootView(final View view) {
                    view.measure(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT);
                    webView.updateFootView(view);
                    return view;
                }
            }, onClickLoadMoreListener);
            hasInit = true;
        }
        return hasInit;
    }

    @Override
    public void setOnScrollBottomListener(View contentView, OnScrollBottomListener onScrollBottomListener) {
        ScrollWebView webView = (ScrollWebView) ((ViewGroup)contentView).getChildAt(0);
        webView.setOnCustomScrollChangeListener(new OnScrollChange(onScrollBottomListener));
    }

    private class OnScrollChange implements ScrollWebView.ScrollInterface {
        private OnScrollBottomListener onScrollBottomListener;

        public OnScrollChange(OnScrollBottomListener onScrollBottomListener) {
            this.onScrollBottomListener = onScrollBottomListener;
        }

        @Override
        public void onSChanged(ScrollWebView webView, int l, int t, int oldl, int oldt) {

            if(!ViewCompat.canScrollVertically(webView, 1)){
                if (onScrollBottomListener != null) {
                    onScrollBottomListener.onScorllBootom();
                }
            }
        }
    }
}
